package controller

import (
	"base/app/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"gorm.io/gorm/clause"
	"strconv"
	"strings"
	"time"
)

type RecordCtl struct {
}

var Record = RecordCtl{}

// 增加record
func (r *RecordCtl) AddRecord(c *gin.Context) {
	//	接受formdata数据
	//file, _ := c.FormFile("filePath")
	keys := []string{"date", "bargeShip", "fisherShip", "audit", "weight", "salvageArea", "disposal", "disposalMethod", "pics", "state", "ymState", "ymText", "pics", "num"}
	var record models.Record
	for _, key := range keys {
		switch key {
		case "date":
			record.Date = c.PostForm("date")
		case "bargeShip":
			record.BargeShip = c.PostForm("bargeShip")
		case "fisherShip":
			record.FisherShip = c.PostForm("fisherShip")
		case "audit":
			record.Audit = c.PostForm("audit")
		case "weight":
			record.Weight = c.PostForm("weight")
		case "salvageArea":
			record.SalvageArea = c.PostForm("salvageArea")
		case "disposal":
			record.Disposal = c.PostForm("disposal")
		case "disposalMethod":
			record.DisposalMethod = c.PostForm("disposalMethod")
		case "pics":
			record.Pics = c.PostForm("pics")
		case "state":
			record.State = c.PostForm("state")
		case "ymState":
			record.YmState = c.PostForm("ymState")
		case "ymText":
			record.YmText = c.PostForm("ymText")
		case "num":
			record.Num = c.PostForm("num")

		}
	}

	//fmt.Println(record)

	// 循环获取为文件，filePath+index，如果没有就跳出循环
	//var paths []string
	//for i := 0; i < 10; i++ {
	//	file, err := c.FormFile("filePath" + strconv.Itoa(i))
	//	if err != nil {
	//		fmt.Println(err)
	//		break
	//	}
	//
	//	nowDateStr := strings.Split(record.Date, " ")[0]
	//	fp := "/public/img/" + nowDateStr + "/" + file.Filename
	//	paths = append(paths, fp)
	//	err = c.SaveUploadedFile(file, fp)
	//}
	//record.Pics = strings.Join(paths, ",")
	//	插入数据库
	//models.Db.Create(&record)
	models.Db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_bargeShip"}},
		DoUpdates: clause.AssignmentColumns([]string{"date", "barge_ship", "fisher_ship", "audit", "num", "weight", "salvage_area", "disposal", "disposal_method", "pics", "state", "ym_state", "ym_text"}),
	}).Create(&record)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": record,
	})

}

// 根据日期和record.State获取record
type queryReq struct {
	Date       string `json:"date"`
	State      string `json:"state"`
	BargeShip  string `json:"bargeShip"`
	FisherShip string `json:"fisherShip"`
	Role       string `json:"role"`
	Username   string `json:"username"`
}

func (r *RecordCtl) GetRecordByDateAndState(c *gin.Context) {
	//	record.State = '全部状态获取全部’
	//date := c.Query("date")
	//state := c.Query("state")
	var req queryReq
	_ = c.ShouldBind(&req)
	var records []models.Record
	//if state == "全部状态" {
	//	models.Db.Where("date = ?", date).Find(&records)
	//} else {
	//	models.Db.Where("date = ? and state = ?", date, state).Find(&records) barge_ship like ? and fisher_ship like ?
	//}
	//date是某一天，records中的date精确到分，获取date当天的所有记录,分别帅选bargeShip和fisherShip，如果为空则不筛选该字段
	var query = models.Db.Where("DATE(date) = ?", req.Date) // 精确匹配日期

	// 如果 state 不是 "全部状态"，则添加 state 条件
	if req.State != "全部状态" {
		query = query.Where("state = ?", req.State)
	}

	// 如果 barge_ship 不为空，则添加 barge_ship 条件
	if req.BargeShip != "" {
		query = query.Where("barge_ship = ?", req.BargeShip) // 精确匹配
	}

	// 如果 fisher_ship 不为空，则添加 fisher_ship 条件
	if req.FisherShip != "" {
		fisherShipArr := strings.Split(req.FisherShip, ",")
		query = query.Where("fisher_ship in (?)", fisherShipArr) // 精确匹配
	}

	// 执行查询
	query.Find(&records)

	//if req.BargeShip != "" || (req.BargeShip == "" && req.FisherShip == "") {
	//	获取每条记录是该驳船所有记录的第几条
	for i, record := range records {
		//	获取该id是barge_ship=record.BargeShip的第几条记录
		var count int64
		models.Db.Model(&models.Record{}).Where("barge_ship = ?", record.BargeShip).Where("id <= ?", record.Id).Count(&count)
		records[i].Bh = strconv.Itoa(int(count))
	}
	//}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": records,
	})
}

// 更新record
func (r *RecordCtl) UpdateRecord(c *gin.Context) {
	var record models.Record
	_ = c.ShouldBind(&record)
	models.Db.Save(&record)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "更新成功",
		"data": record,
	})
}

//	type DisposalRecord struct {
//		BaseModel
//		Date             string `json:"date"`
//		BargeShip        string `json:"bargeShip"`
//		Audit            string `json:"audit"`
//		Weight           string `json:"weight"`
//		DisposalMethod   string `json:"disposalMethod"`
//		DisposalPosition string `json:"disposalPosition"`
//	}
//
// 添加disposalRecord
func (r *RecordCtl) AddDisposalRecord(c *gin.Context) {
	var disposalRecord models.DisposalRecord
	_ = c.ShouldBind(&disposalRecord)
	models.Db.Create(&disposalRecord)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": disposalRecord,
	})
}

// 获取disposalRecord
type queryDisposalReq struct {
	Date      string `json:"date"`
	BargeShip string `json:"bargeShip"`
}

func (r *RecordCtl) GetDisposalRecord(c *gin.Context) {
	var req queryDisposalReq
	_ = c.ShouldBind(&req)
	var disposalRecords []models.DisposalRecord
	//models.Db.Where("DATE(date) = ?", req.Date).Where("barge_ship = ?", req.BargeShip).Find(&disposalRecords)
	if req.BargeShip == "" {
		models.Db.Where("DATE(date) = ?", req.Date).Find(&disposalRecords)
	} else {
		models.Db.Where("DATE(date) = ?", req.Date).Where("barge_ship = ?", req.BargeShip).Find(&disposalRecords)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": disposalRecords,
	})
}

// 获取所有的record
func (r *RecordCtl) GetAllRecord(c *gin.Context) {
	var records []models.Record
	bargeShip := c.Query("bargeShip")
	//获取状态为完成的记录
	if bargeShip == "" {
		models.Db.Find(&records)
	} else {
		models.Db.Where("barge_ship = ?", bargeShip).Find(&records)
	}
	//models.Db.Where("state = ? AND barge_ship = ?", "完成", bargeShip).Find(&records)
	//	数据逐行保存到excel .xlsx文件中
	file := excelize.NewFile()
	title := []string{"日期", "驳船", "渔船", "稽核人员", "有效吊装次数", "携载量", "海域", "图片", "状态"}
	for i, v := range title {
		//为每一列设置宽度
		file.SetColWidth("Sheet1", string(rune(65+i)), string(rune(65+i)), 20)
		if v == "图片" {
			file.SetColWidth("Sheet1", string(rune(65+i)), string(rune(65+i)), 80)
		}
		file.SetCellValue("Sheet1", string(rune(65+i))+"1", v)
	}
	for i, record := range records {
		file.SetCellValue("Sheet1", "A"+strconv.Itoa(i+2), record.Date)
		file.SetCellValue("Sheet1", "B"+strconv.Itoa(i+2), record.BargeShip)
		file.SetCellValue("Sheet1", "C"+strconv.Itoa(i+2), record.FisherShip)
		file.SetCellValue("Sheet1", "D"+strconv.Itoa(i+2), record.Audit)
		file.SetCellValue("Sheet1", "E"+strconv.Itoa(i+2), record.Num)
		file.SetCellValue("Sheet1", "F"+strconv.Itoa(i+2), record.Weight)
		file.SetCellValue("Sheet1", "G"+strconv.Itoa(i+2), record.SalvageArea)
		file.SetCellValue("Sheet1", "I"+strconv.Itoa(i+2), record.State)
		//file.SetCellValue("Sheet1", "G"+strconv.Itoa(i+2), record.Pics)
		//	图片插入为链接
		pics := strings.Split(record.Pics, ",")
		for j, pic := range pics {
			file.SetCellValue("Sheet1", "H"+strconv.Itoa(i+2+j), pic)
		}

	}
	file.SaveAs("public/record.xlsx")

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": "/public/record.xlsx",
	})
}

// 获取昨天14点到今天14点的记录
func (r *RecordCtl) GetYesterdayRecord(c *gin.Context) {
	//	昨天14：00到今天14：00
	//	获取昨天14点到今天14点的记录
	var records []models.Record
	nowDate := time.Now()
	yesterday := nowDate.AddDate(0, 0, -1)
	yesterday14 := time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 14, 0, 0, 0, time.Local)
	today14 := time.Date(nowDate.Year(), nowDate.Month(), nowDate.Day(), 14, 0, 0, 0, time.Local)
	//models.Db.Where("date >= ? and date <= ? and state = ?", yesterday14, today14, "完成").Find(&records)
	bargeShip := c.Query("bargeShip")
	if bargeShip == "" {
		models.Db.Where("date >= ? and date <= ? and state = ?", yesterday14, today14, "完成").Find(&records)
	} else {
		models.Db.Where("date >= ? and date <= ? and state = ? and barge_ship = ?", yesterday14, today14, "完成", bargeShip).Find(&records)
	}
	//	数据逐行保存到excel .xlsx文件中
	file := excelize.NewFile()
	title := []string{"日期", "驳船", "渔船", "稽核人员", "有效吊装次数", "携载量", "海域", "图片"}
	for i, v := range title {
		//为每一列设置宽度
		file.SetColWidth("Sheet1", string(rune(65+i)), string(rune(65+i)), 20)
		if v == "图片" {
			file.SetColWidth("Sheet1", string(rune(65+i)), string(rune(65+i)), 80)
		}
		file.SetCellValue("Sheet1", string(rune(65+i))+"1", v)
	}
	for i, record := range records {
		file.SetCellValue("Sheet1", "A"+strconv.Itoa(i+2), record.Date)
		file.SetCellValue("Sheet1", "B"+strconv.Itoa(i+2), record.BargeShip)
		file.SetCellValue("Sheet1", "C"+strconv.Itoa(i+2), record.FisherShip)
		file.SetCellValue("Sheet1", "D"+strconv.Itoa(i+2), record.Audit)
		file.SetCellValue("Sheet1", "E"+strconv.Itoa(i+2), record.Num)
		file.SetCellValue("Sheet1", "F"+strconv.Itoa(i+2), record.Weight)
		file.SetCellValue("Sheet1", "G"+strconv.Itoa(i+2), record.SalvageArea)
		//file.SetCellValue("Sheet1", "G"+strconv.Itoa(i+2), record.Pics)
		//	图片插入为链接
		pics := strings.Split(record.Pics, ",")
		for j, pic := range pics {
			file.SetCellValue("Sheet1", "H"+strconv.Itoa(i+2+j), pic)
		}

	}
	file.SaveAs("public/yesterdayRecord.xlsx")

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": "/public/yesterdayRecord.xlsx",
	})
}

// 获取所有的disposalRecord
func (r *RecordCtl) GetAllDisposalRecord(c *gin.Context) {
	var disposalRecords []models.DisposalRecord
	models.Db.Find(&disposalRecords)

	//	数据逐行保存到excel .xlsx文件中
	file := excelize.NewFile()
	title := []string{"日期", "驳船", "操作人员", "处置量", "处置方式", "处置位置"}
	for i, v := range title {
		//为每一列设置宽度
		file.SetColWidth("Sheet1", string(rune(65+i)), string(rune(65+i)), 20)
		if v == "处置位置" {
			file.SetColWidth("Sheet1", string(rune(65+i)), string(rune(65+i)), 60)
		}
		file.SetCellValue("Sheet1", string(rune(65+i))+"1", v)
	}
	for i, record := range disposalRecords {
		file.SetCellValue("Sheet1", "A"+strconv.Itoa(i+2), record.Date)
		file.SetCellValue("Sheet1", "B"+strconv.Itoa(i+2), record.BargeShip)
		file.SetCellValue("Sheet1", "C"+strconv.Itoa(i+2), record.Audit)
		file.SetCellValue("Sheet1", "D"+strconv.Itoa(i+2), record.Weight)
		file.SetCellValue("Sheet1", "E"+strconv.Itoa(i+2), record.DisposalMethod)
		file.SetCellValue("Sheet1", "F"+strconv.Itoa(i+2), record.DisposalPosition)
	}

	file.SaveAs("public/disposalRecord.xlsx")

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": "/public/disposalRecord.xlsx",
	})

}

type RowData struct {
	Row [][]string `json:"row"`
}

// 数据导出到excel
func (r *RecordCtl) ExportDataToExcel(c *gin.Context) {
	var req RowData
	_ = c.ShouldBind(&req)
	//	数据逐行保存到excel .xlsx文件中
	file := excelize.NewFile()
	fmt.Println(req)
	//设置每列的宽度
	for i := 0; i < len(req.Row[0]); i++ {
		file.SetColWidth("Sheet1", string(rune(65+i)), string(rune(65+i)), 25)
	}
	for i, row := range req.Row {
		for j, cell := range row {
			file.SetCellValue("Sheet1", string(rune(65+j))+strconv.Itoa(i+1), cell)
		}

	}
	file.SaveAs("public/export.xlsx")

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "导出成功",
		"data": "/public/export.xlsx",
	})
}

// 根据id删除record
func (r *RecordCtl) DeleteRecordById(c *gin.Context) {
	var record models.Record
	id := c.Query("id")
	models.Db.Where("id = ?", id).Delete(&record)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
